import 'package:flutter/material.dart';
import '../models/theory_model.dart';
import '../models/db_helper.dart';

class TheoryDetailPage extends StatefulWidget {
  final TheoryContent content;
  const TheoryDetailPage({Key? key, required this.content}) : super(key: key);

  @override
  State<TheoryDetailPage> createState() => _TheoryDetailPageState();
}

class _TheoryDetailPageState extends State<TheoryDetailPage> {
  late TheoryContent _content;
  late TextEditingController _noteController;
  bool _editingNote = false;
  double _progress = 0.0;

  @override
  void initState() {
    super.initState();
    _content = widget.content;
    _progress = _content.progress;
    _noteController = TextEditingController(text: _content.note ?? '');
  }

  Future<void> _updateContent({bool? isFavorite, bool? isKey, String? note, double? progress, bool? hasNote}) async {
    final newNote = note ?? _noteController.text;
    final updated = TheoryContent(
      id: _content.id,
      jing: _content.jing,
      summary: _content.summary,
      pathogenesis: _content.pathogenesis,
      symptoms: _content.symptoms,
      therapy: _content.therapy,
      formula: _content.formula,
      isFavorite: isFavorite ?? _content.isFavorite,
      hasNote: hasNote ?? (newNote.isNotEmpty),
      isKey: isKey ?? _content.isKey,
      progress: progress ?? _progress,
      lastStudyTime: _content.lastStudyTime,
      note: newNote,
    );
    await DBHelper.updateTheory(updated.toMap());
    setState(() {
      _content = updated;
      _progress = updated.progress;
      if (_noteController.text != (updated.note ?? '')) {
        _noteController.text = updated.note ?? '';
      }
    });
  }

  @override
  void dispose() {
    _noteController.dispose();
    super.dispose();
  }

  Future<bool> _onWillPop() async {
    // 返回时自动保存当前进度和笔记
    if (_progress > _content.progress || (_noteController.text != (_content.note ?? ''))) {
      await _updateContent(progress: _progress, note: _noteController.text, hasNote: _noteController.text.isNotEmpty);
    }
    return true;
  }

  void _onProgressChanged(double value) {
    setState(() {
      _progress = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(
          title: Text('${_content.jing} 详情'),
          backgroundColor: Colors.brown[50],
          elevation: 0,
          actions: [
            IconButton(
              icon: Icon(_content.isFavorite ? Icons.star : Icons.star_border, color: Colors.amber[700]),
              tooltip: _content.isFavorite ? '取消收藏' : '收藏',
              onPressed: () => _updateContent(isFavorite: !_content.isFavorite),
            ),
            IconButton(
              icon: Icon(_content.isKey ? Icons.label_important : Icons.label_important_outline, color: Colors.red),
              tooltip: _content.isKey ? '取消重点' : '标记重点',
              onPressed: () => _updateContent(isKey: !_content.isKey),
            ),
          ],
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: ListView(
            children: [
              Text('六经名：${_content.jing}', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18, color: Colors.brown)),
              const SizedBox(height: 12),
              // 学习进度条与滑块
              Row(
                children: [
                  const Text('学习进度', style: TextStyle(color: Colors.brown)),
                  const SizedBox(width: 8),
                  Expanded(
                    child: LinearProgressIndicator(
                      value: _progress.clamp(0.0, 1.0),
                      minHeight: 8,
                      backgroundColor: Colors.brown.withOpacity(0.1),
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.brown),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text('${(_progress * 100).toInt()}%', style: const TextStyle(color: Colors.brown)),
                ],
              ),
              Slider(
                value: _progress,
                min: 0.0,
                max: 1.0,
                divisions: 20,
                label: '${(_progress * 100).toInt()}%',
                onChanged: (v) => _onProgressChanged(v),
                activeColor: Colors.brown,
                inactiveColor: Colors.brown[100],
              ),
              const SizedBox(height: 16),
              Text('概述：${_content.summary}'),
              Text('病机：${_content.pathogenesis}'),
              Text('症状：${_content.symptoms}'),
              Text('治法：${_content.therapy}'),
              Text('方剂：${_content.formula}'),
              const SizedBox(height: 16),
              if (_content.isFavorite) const Text('已收藏', style: TextStyle(color: Colors.amber)),
              if (_content.isKey) const Text('重点', style: TextStyle(color: Colors.red)),
              // 笔记功能
              const SizedBox(height: 16),
              Row(
                children: [
                  const Text('学习笔记', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown)),
                  const Spacer(),
                  IconButton(
                    icon: Icon(_editingNote ? Icons.save : Icons.edit, color: Colors.brown),
                    tooltip: _editingNote ? '保存笔记' : '编辑笔记',
                    onPressed: () async {
                      if (_editingNote) {
                        await _updateContent(note: _noteController.text, hasNote: _noteController.text.isNotEmpty);
                      }
                      setState(() {
                        _editingNote = !_editingNote;
                      });
                    },
                  ),
                ],
              ),
              _editingNote
                  ? TextField(
                      controller: _noteController,
                      maxLines: 4,
                      decoration: const InputDecoration(
                        hintText: '输入学习笔记...',
                        border: OutlineInputBorder(),
                        isDense: true,
                      ),
                    )
                  : (_content.hasNote
                      ? Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.brown[50],
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(_content.note ?? '', style: const TextStyle(color: Colors.brown)),
                        )
                      : const Text('暂无笔记', style: TextStyle(color: Colors.brown))),
            ],
          ),
        ),
      ),
    );
  }
} 